const Controller = require("egg").Controller;

class BaseController extends Controller {
    //统一函数
    tc(fun) {
        try {
            let res = fun;
            this.success(res);
        } catch (error) {
            this.ctx.status = 501;
            this.ctx.body = "未知错误"
            this.error(error);
        }
    }
    //成功调用
    success(data) {
        if (data.affectedRows !== undefined) {
            console.log(data.affectedRows);
            if (data.affectedRows >= 1) {
                this.ctx.body = {
                    success: true,
                    msg: "操作成功"
                }
            } else {
                this.ctx.body = {
                    success: false,
                    msg: "操作失败"
                }
            }
        } else {
            if (typeof data === "string") {
                this.ctx.body = {
                    success: false,
                    msg: data
                }
            } else {
                this.ctx.body = {
                    success: true,
                    data
                }
            }
        }

    }
    //失败调用
    error(data) {
        this.ctx.body = {
            success: false,
            msg: data
        }
    }
};

module.exports = BaseController;